﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using Modbus.Device;
using SqlSugar.Extensions;
namespace TPressure
{
    public partial class IndexForm : BaseForm
    {
        #region 属性
        /// <summary>串口字典
        ///  串口地址为Key
        /// </summary>
        private Dictionary<string, SerialPort> serialPortDic = new Dictionary<string, SerialPort> { };

        /// <summary>串口字典
        /// 设备编号为Key
        /// </summary>
        private Dictionary<string, SerialPort> deviceSerialPortDic = new Dictionary<string, SerialPort> { };

        /// <summary>点位字典
        /// 
        /// </summary>
        private Dictionary<string, Dictionary<string, object>> masterDic = new Dictionary<string, Dictionary<string, object>> { };

        /// <summary>界面点位字典
        /// 
        /// </summary>
        private Dictionary<string, string> frormPointDic = new Dictionary<string, string> { };

        /// <summary>语音串口
        /// 
        /// </summary>
        private SerialPort voiceSerialPort;

        /// <summary>语音设备地址
        /// 
        /// </summary>
        private string voiceDeviceAddress;

        /// <summary>语音播报状态
        /// 
        /// </summary>
        private bool voiceBroadcastState = false;

        private System.Timers.Timer MCollectTimer;

        private System.Timers.Timer RCollectTimer;

        /// <summary> 曲线开始时间 以此判断曲线的间隔
        /// 
        /// </summary>
        private DateTime chartStartTime;

        /// <summary> 曲线结束时间 以此判断曲线的间隔
        /// 
        /// </summary>
        private DateTime chartEndTime;

        /// <summary> 开始采集
        /// 
        /// </summary>
        private bool startCollect;

        #endregion

        #region 自定义方法
        /// <summary>配置界面
        /// 
        /// </summary>
        private void setupForm()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            this.Divider1.Left = 0;
            this.Divider1.Width = this.Width;
            this.MCollectTimer = new System.Timers.Timer();
            this.MCollectTimer.Interval = 1100;
            this.MCollectTimer.AutoReset = true;//是否重复执行
            this.MCollectTimer.Elapsed += MReadRegister;
            this.GroupBox1.Height = this.Height - this.Header.Height - 85 - this.StatusStrip1.Height;
            this.MChart.Left = this.GroupBox1.Right + 10;
            this.MChart.Top = this.GroupBox1.Top;
            this.MChart.Width = this.Width - this.GroupBox1.Width - 30;
            this.MChart.Height = (this.GroupBox1.Height / 2) - 10;

            this.RChart.Top = this.MChart.Bottom + 10;
            this.RChart.Left = this.MChart.Left;
            this.RChart.Width = this.MChart.Width;
            this.RChart.Height = this.MChart.Height;

            SetupChart(this.MChart);
            SetupChart(this.RChart);
        }

        private void SetupSeries()
        {
            Series mTemplaureSeries = CreateSeries();
            mTemplaureSeries.ChartArea = "Templature";
            mTemplaureSeries.Name = "近端温度";
            this.MChart.Series.Add(mTemplaureSeries);

            Series rTemplaureSeries = CreateSeries();
            rTemplaureSeries.ChartArea = "Templature";
            rTemplaureSeries.Name = "远端温度";
            this.MChart.Series.Add(rTemplaureSeries);

            Series mPressure = CreateSeries();
            mPressure.ChartArea = "Pressure";
            mPressure.Name = "近端压力";
            this.RChart.Series.Add(mPressure);

            Series rPressure = CreateSeries();
            rPressure.ChartArea = "Pressure";
            rPressure.Name = "远端压力";
            this.RChart.Series.Add(rPressure);
        }

        private Series CreateSeries()
        {
            //Series1
            Series series1 = new Series();

            //Series1 style
            series1.ToolTip = "#VALX,#VALY";    //鼠标停留在数据点上，显示XY值

            
            series1.ChartType = SeriesChartType.Spline;  // type
            series1.BorderWidth = 1;

            //Marker
            //series1.MarkerStyle = MarkerStyle.Circle;
            //series1.MarkerSize = 3;
            //series1.MarkerColor = Color.Black;
            series1.SmartLabelStyle.Enabled = true;    // 这里是让标签根据密度转换风格
            series1.XValueType = ChartValueType.DateTime; // 坐标轴type改为时间
            return series1;
        }

        private void SetupChart(Chart chart)
        {
            Chart AzTimeChart = chart;

            this.chartStartTime = DateTime.Now.AddSeconds(0);
            this.MChart.ChartAreas[0].AxisX.Minimum = this.chartStartTime.ToOADate(); // 设置X轴最小值和偏移量
            //this.chartEndTime = DateTime.Now.AddSeconds(10);
            //AzTimeChart.ChartAreas[0].AxisX.Maximum = this.chartEndTime.ToOADate(); // 设置X轴最大值和偏移量  
            //AzTimeChart.ChartAreas[0].AxisX.Interval = 1; // 设置X轴间隔（这里是5秒一个刻度）  
            AzTimeChart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Auto; // 设置间隔类型为秒  
            AzTimeChart.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss"; // 设置X轴标签显示的时间格式

            // 刻度线显示
            AzTimeChart.ChartAreas[0].AxisX.MajorGrid.Enabled = true;
            AzTimeChart.ChartAreas[0].AxisX.MajorGrid.LineWidth = 1;
            AzTimeChart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
        }

        /// <summary>设备列表
        /// 
        /// </summary>
        public void loadDeviceList()
        {
            List<Device> list = SqlSugarHelper.Inquireable<Device>(null);

            foreach (Device item in list)
            {
                Log.Debug("开始联接端口" + item.portAddress);
                string deviceNumber = item.deviceNumber.ToString();
                string portName = item.portAddress; // 串口地址
                int baudRate = item.baudRate;   // 波特率
                var dataBits = 8;      // 数据位
                var stopBits = StopBits.One; // 停止位
                var parity = Parity.None;    // 校验位
                SerialPort serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
                if (!serialPortDic.ContainsKey(item.portAddress))
                {
                    try
                    {
                        serialPort.Open();
                        if (serialPort.IsOpen)
                        {
                            Log.Info(portName + "：端口连接成功");
                            deviceSerialPortDic[item.deviceNumber.ToString()] = serialPort;
                            serialPortDic[item.portAddress] = serialPort;
                        }
                        else
                        {
                            Log.Info(portName + "：端口连接失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(portName + "连接异常：" + ex.Message);
                    }
                }
                else
                {
                    deviceSerialPortDic[deviceNumber] = serialPortDic[item.portAddress];
                    Log.Info(portName + "端口连接成功");
                }
            }

            Task.Run(() =>
            {
                loadDevicePointList();
            });
        }

        /// <summary>设备点位列表
        /// 
        /// </summary>
        public void loadDevicePointList()
        {
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(null);
            foreach (DevicePoint item in list)
            {
                if (deviceSerialPortDic.ContainsKey(item.device_number.ToString()))
                {
                    Dictionary<string, Object> obj = new Dictionary<string, Object> { };
                    obj["slaveAddress"] = item.device_address;
                    obj["startAddress"] = item.point_address;
                    obj["numberOfPoints"] = 1;
                    obj["rangeMin"] = item.range_min;
                    obj["rangeMax"] = item.range_max;
                    obj["signalMin"] = item.out_min;
                    obj["signalMax"] = item.out_max;
                    obj["pointName"] = item.point_name;
                    obj["devicePoint"] = item;
                    SerialPort serialPort = deviceSerialPortDic[item.device_number.ToString()];
                    ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort);
                    master.Transport.WriteTimeout = 1000;
                    master.Transport.ReadTimeout = 1000;
                    obj["master"] = master;
                    obj["serialPort"] = serialPort;
                    obj["deviceAddress"] = item.device_address;
                    masterDic[item.point_number.ToString()] = obj;
                }
                else
                {
                    string log = string.Format("【{0}】连接异常,无法读取【{1}】", item.device_name, item.point_name);
                    Log.Error(log);
                }
            }

            Task.Run(() =>
            {
                loadFormPointList();
            });
        }

        /// <summary>界面点位列表
        /// 
        /// </summary>
        public void loadFormPointList()
        {
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(null);
            foreach (FormPoint item in list)
            {
                frormPointDic[item.form_point_name] = item.device_point_number.ToString();
            }

            Task.Run(() =>
            {
                SetupVoice();
            });

        }

        /// <summary>设置语音
        /// 
        /// </summary>
        private void SetupVoice()
        {
            string key = "voice";

            if (frormPointDic.ContainsKey(key))
            {
                string pointNumber = frormPointDic[key];
                if (masterDic.ContainsKey(pointNumber))
                {
                    Dictionary<string, object> dic = masterDic[pointNumber];
                    voiceSerialPort = (SerialPort)dic["serialPort"];
                    voiceDeviceAddress = dic["deviceAddress"].ToString();
                    int address = voiceDeviceAddress.ObjToInt();
                    voiceDeviceAddress = address.ToString("00");
                    voiceSerialPort.DataReceived += new SerialDataReceivedEventHandler(receivedData);//接收数据事件
                    voiceSerialPort.ReadTimeout = 3;
                    try
                    {
                        Byte[] strbyte = Tool.HexStringToBytes("CCDDAA");
                        voiceSerialPort.Write(strbyte, 0, strbyte.Length);//发送数据
                    }
                    catch (Exception ex)
                    {
                        Log.Error("语音模块联接指令下发异常：" + ex.Message);
                    }
                }
                else
                {
                    Log.Debug("语音master未创建");
                }
            }
        }

        /// <summary>收到串口回复
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void receivedData(object sender, SerialDataReceivedEventArgs e)//接收数据
        {
            SerialPort serialPort = (SerialPort)sender;

            int len = serialPort.BytesToRead;//获取可以读取的字节数

            byte[] buff = new byte[len];//创建缓存数据数组

            try
            {
                serialPort.Read(buff, 0, len);//把数据读取到buff数组

                Invoke((new Action(() =>
                {
                    string back = BitConverter.ToString(buff, 0, buff.Length).Replace("-", "");
                    if (back.Contains("CCDDAA"))
                    {
                        Log.Info("语音模块已联接");
                        voiceBroadcastState = true;
                        if (voiceBroadcastState)
                        {
                            Broadcast("开机，请建立工程");
                        }
                    }
                })));
            }
            catch (Exception ex)
            {
                Log.Error("读取串口回复数据异常：" + ex.Message);
            }
        }

        /// <summary>播报
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void Broadcast(string content)
        {
            Log.Debug("语音播报：" + content);

            string lengthString = Tool.StringByteLength(content).ToString("X");
            if (lengthString.Length < 2)
            {
                lengthString = "0" + lengthString;
            }
            Log.Info(string.Format("数据长度:{0}", lengthString));
            string hexContent = Tool.GetHexFromChs(content);
            Log.Info(string.Format("数据内容:{0}", hexContent));

            string command = voiceDeviceAddress + "1000000000" + lengthString + hexContent;
            Log.Info(string.Format("指令:{0}", command));

            string crc = Tool.CRCForModbus(command);
            command = command + crc;
            if (voiceSerialPort != null)
            {
                if (voiceSerialPort.IsOpen)
                {
                    Byte[] strbyte = Tool.HexStringToBytes(command);
                    voiceSerialPort.Write(strbyte, 0, strbyte.Length);//发送数据
                    Log.Info(string.Format("下发播报指令：{0}", command));
                }
                else
                {
                    Log.Info("联接错误，无法下发播报指令");
                }
            }
        }
        /// <summary>读取寄存器
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MReadRegister(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime now = DateTime.Now;
            bool[] res = ReadCoilsAsync("MFan", 1);
            if (res != null)
            {
                Log.Debug("主风扇状态：" + res[0]);
            }
            else
            {
                Log.Error("主机箱风扇获取失败");
            }


            Thread.Sleep(100);
            Dictionary<string, object>  back =ReadInputRegistersAsync("MTemplature");
            Color backgroundColor = Color.Green;
            Color textColor = Color.White;
            if (back != null)
            {
                
                ushort[] shorts = (ushort[])back["data"];
                DevicePoint point = (DevicePoint)back["devicePoint"];
                float temperature = (Tool.ConvertUshort(shorts[0]) / 10.0f);
                this.MChart.Series[0].Points.AddXY(now, temperature);
                if (temperature > point.alarm_hight)
                {
                    backgroundColor = Color.Red;
                    string msg = string.Format("【{0}:】【{1}】超过限高阈值【{2}】", point.point_name, temperature, point.alarm_hight);
                    Log.Debug(msg);
                }
                else
                {
                    backgroundColor = Color.Green;
                    string msg = string.Format("【{0}:】【{1}】", point.point_name, temperature);
                    Log.Debug(msg);
                }
                MTemperatureInput.Text = temperature.ToString();
                this.MTemperatureInput.BackColor = backgroundColor;
                this.MTemperatureInput.ForeColor = textColor;
            }
            else
            {
                Log.Error("主机箱温度获取失败");
            }

            res = ReadCoilsAsync("RFan", 2);
            if (res != null)
            {
                Log.Debug(string.Format("远端风扇：【{0}】 采集标志：【{1}】", res[0], res[1]));
            }
            else
            {
                Log.Error("远端机箱风扇获取失败");
            }

            Thread.Sleep(100);
            backgroundColor = Color.Green;
            back = ReadInputRegistersAsync("RTemplature");
            if (back != null)
            {
                ushort[] shorts = (ushort[])back["data"];
                DevicePoint point = (DevicePoint)back["devicePoint"];
                float temperature = (Tool.ConvertUshort(shorts[0]) / 10.0f);
                this.MChart.Series[1].Points.AddXY(now, temperature);
                if (temperature > point.alarm_hight)
                {
                    backgroundColor = Color.Red;
                    string msg = string.Format("【{0}:】【{1}】超过限高阈值【{2}】", point.point_name,temperature,point.alarm_hight);
                    Log.Debug(msg);
                }
                else
                {
                    backgroundColor = Color.Green;
                    string msg = string.Format("【{0}:】【{1}】", point.point_name, temperature);
                    Log.Debug(msg);
                }
                RTemperatureInput.Text = temperature.ToString();
                this.RTemperatureInput.BackColor = backgroundColor;
                this.RTemperatureInput.ForeColor = textColor;
            }
            else
            {
                Log.Error("远机箱温度获取失败");
            }


            ReadInputsAsync("MCollect");

            Thread.Sleep(100);
            backgroundColor = Color.Green;
            back = ReadHoldingRegistersAsync("MPressure");
            if (back != null)
            {
                ushort[] shorts = (ushort[])back["data"];

                DevicePoint point = (DevicePoint)back["devicePoint"];
                
                float outMax = point.out_max;

                float outMin = point.out_min;

                float rangeMax = point.range_max;

                float rangeMin = point.range_min;

                double pressure = (shorts[0] - outMin) / (outMax - outMin);
                pressure = Math.Round(pressure * (rangeMax - rangeMin) + rangeMin, 1);
                this.RChart.Series[0].Points.AddXY(now, 10);
                if (pressure > point.alarm_hight)
                {
                    backgroundColor = Color.Red;
                    string msg = string.Format("【{0}:】【{1}】超过限高阈值【{2}】", point.point_name, pressure, point.alarm_hight);
                    Log.Debug(msg);
                }
                else if (pressure < point.alarm_low)
                {
                    backgroundColor = Color.Red;
                    string msg = string.Format("【{0}:】【{1}】低于最低阈值【{2}】", point.point_name, pressure, point.alarm_hight);
                    Log.Debug(msg);
                }
                else
                {
                    backgroundColor = Color.Green;
                    string msg = string.Format("【{0}:】【{1}】", point.point_name, pressure);
                    Log.Debug(msg);
                }
                MPressureLabel.Text = pressure.ToString();
                this.MPressureLabel.BackColor = backgroundColor;
                this.MPressureLabel.ForeColor = textColor;
            }
            else
            {
                Log.Error("主压力获取失败");
            }

            Thread.Sleep(100);
            backgroundColor = Color.Green;
            back = ReadHoldingRegistersAsync("RPressure");
            if (back != null)
            {
                ushort[] shorts = (ushort[])back["data"];

                DevicePoint point = (DevicePoint)back["devicePoint"];

                float outMax = point.out_max;

                float outMin = point.out_min;

                float rangeMax = point.range_max;

                float rangeMin = point.range_min;

                double pressure = (shorts[0] - outMin) / (outMax - outMin);
                pressure = Math.Round(pressure * (rangeMax - rangeMin) + rangeMin, 1);
                this.RChart.Series[1].Points.AddXY(now, pressure);
                if (pressure > point.alarm_hight)
                {
                    backgroundColor = Color.Red;
                    string msg = string.Format("【{0}:】【{1}】超过限高阈值【{2}】", point.point_name, pressure, point.alarm_hight);
                    Log.Debug(msg);
                }
                else if (pressure < point.alarm_low)
                {
                    backgroundColor = Color.Red;
                    string msg = string.Format("【{0}:】【{1}】低于最低阈值【{2}】", point.point_name, pressure, point.alarm_hight);
                    Log.Debug(msg);
                }
                else
                {
                    backgroundColor = Color.Green;
                    string msg = string.Format("【{0}:】【{1}】", point.point_name, pressure);
                    Log.Debug(msg);
                }
                RPressureLabel.Text = pressure.ToString();
                this.RPressureLabel.BackColor = backgroundColor;
                this.RPressureLabel.ForeColor = textColor;
            }
            else
            {
                Log.Error("远压力获取失败");
            }
        }

        private bool[] ReadCoilsAsync(string key, int count)
        {

            if (frormPointDic.ContainsKey(key))
            {
                string pointNumber = frormPointDic[key];


                if (masterDic.ContainsKey(pointNumber))
                {
                    Dictionary<string, object> dic = masterDic[pointNumber];

                    ModbusSerialMaster master = (ModbusSerialMaster)dic["master"];

                    // 从设备地址
                    byte slaveAddress = (byte)dic["slaveAddress"].ToString().ObjToInt();

                    // 读取起始寄存器地址
                    ushort startAddress = ushort.Parse(dic["startAddress"].ToString());

                    // 读取寄存器数量
                    ushort numberOfPoints = ushort.Parse(dic["numberOfPoints"].ToString());

                    if (count > 1)
                    {
                        numberOfPoints = ushort.Parse(count.ToString());
                    }

                    try
                    {
                        Task<bool[]> task = master.ReadCoilsAsync(slaveAddress, startAddress, numberOfPoints);

                        bool[] shorts = task.Result;
                        return shorts;
                        /*
                        bool fanState = shorts[0];

                        Log.Debug(dic["pointName"] + " 状态：" + fanState);
                        if (key == "RFan" && count > 1)
                        {
                            if (shorts.Length > 1)
                            {
                                fanState = shorts[1];
                                Log.Debug("指示灯状态：" + fanState);
                            }
                        }*/
                    }
                    catch (Exception ex)
                    {
                        Log.Error(dic["pointName"] + " 状态异常：" + ex.Message);
                        return null;
                    }
                }
                else
                {
                    Log.Error(key + " master未创建");
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        private Dictionary<string, object> ReadInputRegistersAsync(string key)
        {
            if (frormPointDic.ContainsKey(key))
            {
                string pointNumber = frormPointDic[key];

                if (masterDic.ContainsKey(pointNumber))
                {
                    Dictionary<string, object> dic = masterDic[pointNumber];

                    ModbusSerialMaster master = (ModbusSerialMaster)dic["master"];

                    // 从设备地址
                    byte slaveAddress = (byte)dic["slaveAddress"].ToString().ObjToInt();

                    // 读取起始寄存器地址
                    ushort startAddress = ushort.Parse(dic["startAddress"].ToString());

                    // 读取寄存器数量
                    ushort numberOfPoints = ushort.Parse(dic["numberOfPoints"].ToString());
                    Task<ushort[]> task = master.ReadInputRegistersAsync(slaveAddress, startAddress, numberOfPoints);
                    try
                    {
                        ushort[] shorts = task.Result;
                        Dictionary<string, object> back = new Dictionary<string, object>();
                        back["data"] = shorts;
                        back["devicePoint"] = dic["devicePoint"];
                        return back;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(dic["pointName"] + " 温度异常：" + ex.Message);
                        return null;
                    }
                }
                else
                {
                    Log.Error(key + " master未创建");
                    return null;
                }
            }
            else
            {
                Log.Debug(key + " 界面点位未创建");
                return null;
            }
        }

        private bool[] ReadInputsAsync(string key)
        {
            if (frormPointDic.ContainsKey(key))
            {
                string pointNumber = frormPointDic[key];

                if (masterDic.ContainsKey(pointNumber))
                {
                    Dictionary<string, object> dic = masterDic[pointNumber];

                    ModbusSerialMaster master = (ModbusSerialMaster)dic["master"];

                    // 从设备地址
                    byte slaveAddress = (byte)dic["slaveAddress"].ToString().ObjToInt();

                    // 读取起始寄存器地址
                    ushort startAddress = ushort.Parse(dic["startAddress"].ToString());

                    // 读取寄存器数量
                    ushort numberOfPoints = ushort.Parse(dic["numberOfPoints"].ToString());
                    Task<bool[]> task = master.ReadInputsAsync(slaveAddress, startAddress, numberOfPoints);
                    try
                    {
                        bool[] shorts = task.Result;
                        return shorts;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(dic["pointName"] + " 状态获取异常：" + ex.Message);
                        return null;
                    }
                }
                else
                {
                    Log.Debug(key + " master未创建");
                    return null;
                }
            }
            else
            {

                Log.Debug(key + " 界面点位未创建");
                return null;
            }
        }
        private Dictionary<string, object> ReadHoldingRegistersAsync(string key)
        {
            if (frormPointDic.ContainsKey(key))
            {
                string pointNumber = frormPointDic[key];


                if (masterDic.ContainsKey(pointNumber))
                {
                    Dictionary<string, object> dic = masterDic[pointNumber];

                    ModbusSerialMaster master = (ModbusSerialMaster)dic["master"];

                    // 从设备地址
                    byte slaveAddress = (byte)dic["slaveAddress"].ToString().ObjToInt();

                    // 读取起始寄存器地址
                    ushort startAddress = ushort.Parse(dic["startAddress"].ToString());

                    // 读取寄存器数量
                    ushort numberOfPoints = ushort.Parse(dic["numberOfPoints"].ToString());
                    Task<ushort[]> task = master.ReadHoldingRegistersAsync(slaveAddress, startAddress, numberOfPoints);

                    try
                    {
                        ushort[] shorts = task.Result;
                        Dictionary<string, object> back = new Dictionary<string, object>();
                        back["data"] = shorts;
                        back["devicePoint"] = dic["devicePoint"];
                        return back;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(dic["pointName"] + " 结果获取异常：" + ex.Message);
                        return null;
                    }
                }
                else
                {
                    Log.Debug(key + " master未创建");
                    return null;
                }
            }
            else
            {
                Log.Debug(key + " 界面点位未创建");
                return null;
            }
        }

        #endregion

        #region 系统方法
        /// <summary>当前时间
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NowTimer_Tick(object sender, EventArgs e)
        {
            TimeLabel.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        public IndexForm()
        {
            InitializeComponent();
            this.FullScreen = true;
            
        }

        private void IndexForm_Load(object sender, EventArgs e)
        {
            setupForm();
            NowTimer_Tick(this.NowTimer, null);
            Task.Run(() =>
            {
                loadDeviceList();
            });
        }

        #endregion

        #region 快捷按钮事件

        private void CollectButton_Click(object sender, EventArgs e)
        {
            if (!startCollect)
            {
                this.MChart.Series.Clear();
                this.RChart.Series.Clear();
                SetupSeries();
                this.chartStartTime = DateTime.Now;
                this.MChart.ChartAreas[0].AxisX.Minimum = this.chartStartTime.ToOADate();
                this.RChart.ChartAreas[0].AxisX.Minimum = this.chartStartTime.ToOADate();
                this.MCollectTimer.Start();
                this.CollectButton.Text = "停止采集";
                this.startCollect = true;
            }
            else
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "您确定要停止采集吗？")
                {
                    OnOk = config =>
                    {
                        this.MCollectTimer.Stop();
                        this.CollectButton.Text = "开始采集";
                        this.startCollect = false;
                        return true;
                    },
                });
            }
        }

        /// <summary>设备管理
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceManageButton_Click(object sender, EventArgs e)
        {
            DeviceManageForm frm = new DeviceManageForm();
            frm.ShowDialog();
        }

        private void TemplateButton_Click(object sender, EventArgs e)
        {
            TemplateManageForm frm = new TemplateManageForm();
            frm.ShowDialog();
        }

        private void AddTemplateButton_Click(object sender, EventArgs e)
        {
            AddTemplateForm frm = new AddTemplateForm();
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void AddProjectButton_Click(object sender, EventArgs e)
        {
            AddProjectForm frm = new AddProjectForm();
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void ProjectButton_Click(object sender, EventArgs e)
        {
            ProjecManagetForm frm = new ProjecManagetForm();
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void FormPointButton_Click(object sender, EventArgs e)
        {
            FormPointManageForm frm = new FormPointManageForm();
            frm.Owner = this;
            frm.ShowDialog();
        }

        #endregion
    }
}
